<template>
  <bd-popup
    class="custom"
    popupId="lotteryV3SettlementResult"
    v-model:show="props.show"
    :style="{
      'background-color': 'transparent',
      padding: '0 30px 30px 30px !important',
    }"
    :overlay-style="{
      background: 'rgba(0, 0, 0, 0.5)',
    }"
    zIndex="999999"
    teleport="body"
    :close-on-click-overlay="false"
    :weights="1"
  >
    <img class="hdj" src="/image/lottery-v3/winning-result-hdj.png" />
    <div class="box" :class="{ 'box-fri': lotteryStore.isFri }">
      <!-- 标题 -->
      <div class="title">
        <img
          v-if="!lotteryStore.isFri"
          class="title-bg"
          src="/image/lottery-v3/winningResult-title.svg"
        />
        <img
          v-else
          class="title-bg"
          src="/image/lottery-v3/winningResult-title1.svg"
        />
        <div class="title-text">
          {{ $t("lotteryMoney.ztzjjg") }}
        </div>
      </div>
      <!-- 奖金 -->
      <div class="bonus items-center">
        <img
          v-if="lotteryStore.isFri"
          class="bonus-bg"
          src="/image/lottery-v3/settlement-bonus-bg1.png"
        />
        <img
          v-else
          class="bonus-bg"
          src="/image/lottery-v3/settlement-bonus-bg.png"
        />
        <!-- 美金 -->
        <div class="bonus-item items-center">
          <div class="bonus-item-top items-center">
            <img class="bonus-item-top-icon" src="/image/money-blue.svg" />
            <div class="bonus-item-top-text">
              {{ $t("lotteryMoney.bonus") }}
            </div>
          </div>
          <div
            class="bonus-item-bottom"
            :class="{ 'bonus-item-bottom-fri': lotteryStore.isFri }"
          >
            ${{ toThousands(decimalToLength(source.dollarPrizeAmount || 0)) }}
          </div>
        </div>
        <!-- 分割线 -->
        <div class="bonus-line"></div>
        <!-- BDC -->
        <div class="bonus-item items-center">
          <div class="bonus-item-top items-center">
            <img class="bonus-item-top-icon" src="/image/bdc.svg" />
            <div class="bonus-item-top-text">BDC</div>
          </div>
          <div
            class="bonus-item-bottom"
            :class="{ 'bonus-item-bottom-fri': lotteryStore.isFri }"
          >
            {{ toThousands(source.bdcPrizeAmount || 0) }} BDC
          </div>
        </div>
      </div>
      <!-- 奖项 -->
      <div class="award">
        <!-- 一等奖和二等奖 -->
        <template v-if="userPrizeDetailArr">
          <div
            class="award-item items-center"
            v-for="(item, index) in userPrizeDetailArr"
            :key="index"
          >
            <div class="items-center">
              <div class="award-item-left items-center">
                <img
                  v-if="item.prizeLevel == 1"
                  class="award-item-left-icon"
                  src="/image/lottery-v3/result-ydj-icon.svg"
                />
                <img
                  v-else-if="item.prizeLevel == 2"
                  class="award-item-left-icon"
                  src="/image/lottery-v3/result-edj-icon.svg"
                />
                <div class="award-item-left-text">
                  {{
                    $t(
                      item.prizeLevel == 1
                        ? "lotteryMoney.ydj"
                        : "lotteryMoney.edj"
                    )
                  }}
                </div>
              </div>
              <div class="award-item-center items-center">
                <div
                  class="award-item-center-item"
                  v-for="(num, idx) in item.drawNoArr"
                  :key="idx"
                >
                  <img
                    v-if="num.include && !lotteryStore.isFri"
                    class="award-item-center-item-bg"
                    src="/image/lottery-v3/num-zj-bg1.svg"
                  />
                  <img
                    v-else-if="num.include && lotteryStore.isFri"
                    class="award-item-center-item-bg"
                    src="/image/lottery-v3/num-zjfri-bg1.svg"
                  />
                  <img
                    v-else
                    class="award-item-center-item-bg"
                    src="/image/lottery-v3/num-xz-bg1.svg"
                  />
                  <div
                    class="award-item-center-item-text"
                    :class="{ 'award-item-center-item-text-xz': !num.include }"
                  >
                    {{ num.str }}
                  </div>
                </div>
                <!-- 数量 -->
                <div class="award-item-center-text">*{{ item.drawCount }}</div>
              </div>
            </div>
            <div class="award-item-right">
              ${{ toThousands(decimalToLength(item.prizeAmount || 0)) }}
            </div>
          </div>
        </template>
        <!-- 三等奖 -->
        <div v-if="source.thirdPrizeLevel" class="award-item items-center">
          <div class="award-item-left items-center">
            <img
              class="award-item-left-icon"
              src="/image/lottery-v3/result-sdj-icon.svg"
            />
            <div class="award-item-left-text">
              {{ $t("lotteryMoney.sdj") }}
            </div>
          </div>
          <div class="award-item-right">
            <div style="margin-bottom: 1.5px; white-space: nowrap">
              ({{ source.thirdPrizeLevel.prizeCount
              }}{{ $t("lotteryMoney.xxz") }})
              {{
                toThousands(
                  decimalToLength(source.thirdPrizeLevel.prizeAmount || 0)
                )
              }}
              BDC
            </div>
            <div style="color: #999da7">{{ $t("lotteryMoney.zryff") }}</div>
          </div>
        </div>
        <!-- 参与奖 -->
        <div
          v-if="source.participationPrizeLevel"
          class="award-item award-item-end items-center"
          style="padding-bottom: 0"
        >
          <div class="award-item-left items-center">
            <img
              class="award-item-left-icon"
              src="/image/lottery-v3/result-cyj-icon.svg"
            />
            <div class="award-item-left-text">
              {{ $t("lotteryMoney.cyj") }}
            </div>
          </div>
          <div class="award-item-right">
            <div style="margin-bottom: 1.5px; white-space: nowrap">
              ({{ source.participationPrizeLevel.prizeCount
              }}{{ $t("lotteryMoney.xxz") }})
              {{
                toThousands(
                  decimalToLength(
                    source.participationPrizeLevel.prizeAmount || 0
                  )
                )
              }}
              BDC
            </div>
            <div style="color: #999da7">
              {{ $t("lotteryMoney.zryff") }}
            </div>
          </div>
        </div>
      </div>
      <!-- footer 按钮 -->
      <div class="footer items-center">
        <img
          v-if="lotteryStore.isFri"
          class="footer-bg"
          src="/image/lottery-v3/settlement-footer-bg1.svg"
        />
        <img
          v-else
          class="footer-bg"
          src="/image/lottery-v3/settlement-footer-bg.svg"
        />
        <!-- 兑奖 -->
        <div
          class="footer-item"
          :class="{
            'footer-item-fri': lotteryStore.isFri,
          }"
          @click.stop="confirm(1)"
        >
          {{ $t("lotteryMoney.djBtn") }}
        </div>
        <!-- 分享 -->
        <div
          class="footer-item footer-item-maxwidth"
          :class="{ 'footer-item-fri': lotteryStore.isFri }"
          @click.stop="confirm(2)"
        >
          {{ $t("lotteryMoney.fxghy") }}
        </div>
      </div>
    </div>
    <!-- 关闭 -->
    <img
      class="close"
      src="/image/close-fff-icon.svg"
      @click.stop="closePopup"
    />
  </bd-popup>
</template>
<script setup lang="ts" name="settlementResultPopup">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { useClipboard } from "@vueuse/core";
import { useLotteryV3Store } from "~/store/modules/lottery-v3";
import { useGlobalStore } from "~~/store/global";

interface SettlementInfo {
  bdcPrizeAmount?: string; // BDC奖金数量
  dollarPrizeAmount?: string; // 美金奖金数量
  userPrizeDetailList?: any; // 一等奖 和 二等奖
  thirdPrizeLevel?: any; // 三等奖
  participationPrizeLevel?: any; // 参与奖
}

const props = withDefaults(
  defineProps<{
    show: boolean;
    source: SettlementInfo; // 中奖消息
  }>(),
  {
    show: false,
  }
);

const emit = defineEmits(["update:show"]);

const lotteryStore = useLotteryV3Store();

const { t } = useI18n();
const firebase = useInitFirebase(); // 初始化firebase

const globalStore = useGlobalStore();
// 资源
const file = getOssFileUrl({
  avatarDefault: "/image/avatar-default.png",
  sharePage: "/invite-friends/v3/invite",
});

// 分享地址
const shareUrl = computed(() => {
  return (
    file.sharePage +
    "?hiddenBar=1" +
    `&language=${globalStore.$state.language}` +
    `&packageId=${globalStore.$state.packageId}` +
    `&sourceType=12` +
    `&code=${lotteryStore.$state.inviteLotteryCode}`
  );
});

/**
 * @description: 匹配中奖号码
 * 1. 重复出现的数字,要根据数量显示
 * @param {*} a 中奖号码
 * @param {*} b 下注号码
 * @return {*} c 下注号码,与中奖号码匹配的结果
 * @author: zhj1214
 */
const includesNumToArr = (a: string, b: string) => {
  const charMapA = new Map();

  // 构建字符映射表，记录字符在 a 中的数量
  for (let char of a) {
    charMapA.set(char, (charMapA.get(char) || 0) + 1);
  }

  let c = [];
  for (let char of b) {
    const countInA = charMapA.get(char);
    if (countInA && countInA > 0) {
      c.push({ str: char, include: true });
      charMapA.set(char, countInA - 1);
    } else {
      c.push({ str: char, include: false });
    }
  }
  return c;
};

const userPrizeDetailArr = computed(() => {
  if (
    props.source.userPrizeDetailList &&
    props.source.userPrizeDetailList.length > 0
  ) {
    return props.source.userPrizeDetailList.map((e: any) => {
      e.drawNoArr = includesNumToArr(e.hashScore, e.drawNo);
      return e;
    });
  }
  return [];
});

onMounted(() => {});
onBeforeUnmount(() => {});

// 关闭弹窗
const closePopup = () => {
  // https://etherscan.io/tx/0xfcde0e9d888949df20e6c86b8cc4dd0456a3b30fd6f6a44d540d285375d54f00
  emit("update:show", false);
};

/****************** 分享 ******************/
const saveCopy = () => {
  if (!file.sharePage) return;
  const { copy, isSupported } = useClipboard({
    source: "",
  });
  if (!isSupported.value) {
    showToast({
      message: t("mvp.other.bzcjtb"),
      "z-index": 9999999,
    });
  } else {
    copy(shareUrl.value);
    showToast({
      message: t("mvp.other.fzcg"),
      "z-index": 9999999,
    });
  }
};

let shareLoading = false;
const shareApp = () => {
  if (shareLoading) return;
  try {
    shareLoading = true;
    saveCopy();
    console.log("分享地址:", shareUrl.value);
    bridge.onShare(t("lotteryMoney.hyzldmfcj"), shareUrl.value);
    firebase?.logEvent("BDC_H5_LotteryV3_inviteFriends_shareApp_Click"); // 埋点访问
  } catch (error) {
    console.log(error);
  } finally {
    // 延时 1s，防止用户连续点击
    setTimeout(() => {
      shareLoading = false;
    }, 1000);
  }
};

/****************** 按钮逻辑 ******************/

/**
 * @description: 按钮逻辑: 1,兑奖 2,分享好友
 */
const confirm = (val: number) => {
  if (val == 1) {
    firebase?.logEvent("BDC_H5_LotteryV3_BDCToMoney_Click"); // 埋点访问
    navigateI18nTo({ path: "/lottery-v3/bdc-to-money" });
  } else if (val == 2) {
    shareApp();
  }
  closePopup();
};
</script>
<style lang="scss" scoped>
.hdj {
  position: relative;
  z-index: 9;
  margin-left: 50%;
  transform: translateX(-50%);
  margin-bottom: -10 * 2px;
  width: 140 * 2px;
  height: 50 * 2px;
}
.title {
  position: relative;
  width: 100%;
  justify-content: center;
  &-bg {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 0;
    width: 303 * 2px;
    height: 30 * 2px;
  }
  &-text {
    position: relative;
    z-index: 9;
    height: 30 * 2px;
    line-height: 30 * 2px;
    text-align: center;

    color: #fff;
    font-size: 15 * 2px;
    font-weight: 590;
  }
}
.box {
  position: relative;
  border-radius: 12 * 2px;
  border: 4 * 2px solid #09f;
  background: #fff;
  padding: 14 * 2px 10 * 2px 0 * 2px 10 * 2px;
  &-fri {
    border: 4 * 2px solid #ff9b01;
  }
}
.bonus {
  position: relative;
  width: 100%;
  height: 133 * 2px;
  justify-content: center;
  margin-bottom: 10 * 2px;

  &-bg {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    object-fit: cover;
  }
  &-line {
    position: relative;
    z-index: 9;
    width: 0;
    margin-top: 63 * 2px;
    height: 30 * 2px;
    border: 0.8px dashed rgba(0, 123, 255, 0.15);
  }
  &-item {
    position: relative;
    z-index: 9;
    flex-direction: column;
    justify-content: center;
    margin-top: 63 * 2px;
    width: calc(50% - 21 * 2px);
    &-top {
      margin-bottom: 5 * 2px;
      &-icon {
        width: 18 * 2px;
        height: 18 * 2px;
        margin-right: 4 * 2px;
      }
      &-text {
        color: #141924;
        font-size: 12 * 2px;
        font-weight: 590;
      }
    }
    &-bottom {
      color: #007bff;
      font-size: 14 * 2px;
      font-weight: 590;
      &-fri {
        color: #ff9b01;
      }
    }
  }
}

.award {
  border-radius: 4 * 2px;
  border: 0.7px solid rgba(115, 119, 128, 0.15);
  padding: 5 * 2px;
  margin-bottom: 5 * 2px;

  max-height: 198 * 2px;
  overflow-y: scroll;
  overflow-x: hidden;

  &-item {
    justify-content: space-between;
    padding-bottom: 8 * 2px;
    border-bottom: 0.7px solid rgba(115, 119, 128, 0.15);
    margin-bottom: 8 * 2px;

    &-end {
      border-bottom: none;
      margin-bottom: 0 * 2px;
    }

    &-bm0 {
      padding-bottom: 0;
      border-bottom: none;
      margin-bottom: 0;
    }

    &-left {
      width: 130 * 2px;
      &-icon {
        width: 18 * 2px;
        height: 18 * 2px;
        margin-right: 2 * 2px;
      }
      &-text {
        color: #002853;
        font-size: 11 * 2px;
        font-weight: 400;
      }
    }
    &-center {
      &-item {
        position: relative;
        width: 14 * 2px;
        height: 14 * 2px;
        justify-content: center;
        margin-right: 2 * 2px;
        &-bg {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        &-text {
          position: relative;
          z-index: 9;
          color: #fff;
          font-size: 11 * 2px;
          font-weight: 590;
          line-height: 14 * 2px;
          text-align: center;
          &-xz {
            color: #8e96a4;
          }
        }
      }
      &-text {
        color: #002853;
        font-size: 11 * 2px;
        font-weight: 400;
      }
    }
    &-right {
      color: #002853;
      font-size: 11 * 2px;
      font-weight: 400;
      text-align: right;
    }
  }
}

.footer {
  position: relative;
  z-index: 10;
  width: calc(100% + 14 * 4px);
  margin-left: -14 * 2px;
  margin-bottom: -4.5 * 2px;
  height: 83 * 2px;
  justify-content: space-evenly;

  &-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  &-item {
    position: relative;
    margin-top: 15 * 2px;
    z-index: 11;
    width: calc(50% - 15 * 6px);
    height: 36 * 2px;
    line-height: 36 * 2px;
    text-align: center;

    color: #007bff;
    font-size: 15 * 2px;
    font-weight: 590;
    border-radius: 4 * 2px;
    background: rgba(255, 255, 255, 0.8);

    &-fri {
      color: #ff9b01;
    }
  }
}

.close {
  position: relative;
  z-index: 9;
  bottom: -30 * 2px;
  left: 50%;
  transform: translateX(-50%);
  width: 30 * 2px;
  height: 30 * 2px;
}
</style>
